package com.jh.microservice.reactive;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CompletableFutureDemo {

    public static void main(String[] args) {

        print("当前线程");

        ExecutorService executor = Executors.newFixedThreadPool(2);

        /**
         * 一开始弄了一个线程去执行第一步的生产消息，
         * 第二步不管是thenApply还是thenApplyAsync，
         * 由于没有必要去再开启一个线程去接收结果进行处理，直接源用第一个步骤生成的线程
         */
        CompletableFuture.supplyAsync(() -> {
            print("第一步：返回Hello");
            return "Hello";
        }).thenApplyAsync(result -> {
            print("第二步：拼接第一步结果 + World");
            return result + "World";
        }).thenAccept(CompletableFutureDemo::print)
                .whenComplete((v, e) -> {
                    print("执行完成");
                })
                .join();

        // 每次都开启一个线程处理任务
        /*CompletableFuture.supplyAsync(() -> {
            print("第一步：返回Hello");
            return "Hello";
        }, executor).thenApplyAsync(result -> {
            print("第二步：拼接第一步结果 + World");
            return result + "World";
        }, executor).thenAccept(CompletableFutureDemo::print);*/

        executor.shutdown();
    }

    public static void print(String message) {
        System.out.printf("【线程：%s】：%s\n", Thread.currentThread().getName(), message);
    }

}
